package sysUtil

import com.auth0.jwt.JWT
import com.auth0.jwt.JWTVerifier
import com.auth0.jwt.algorithms.Algorithm
import sysAuth.SysViewCfg

/**
 * Created by Administrator on 2018-10-22.
 */
class JwtToken {
    //公共密匙
    static String SECRET = "CopyRight@xxd"

    static String USER_NO = "userNo"
    static String USER_NAME = "userName"
    //有效时长
    static int SESSION_MINUTE = 60
    /**
     * 加密
     * @param user
     * @return
     */
    static String create(String userNo,String userName){
        Calendar calendar = Calendar.getInstance()
        Date now = calendar.getTime()
        calendar.add(Calendar.MINUTE,SysViewCfg.first().tokenTime?:SESSION_MINUTE )
        Date expDate = calendar.getTime()

        Map head = [:]
        head.put("typ","JWT")
        head.put("alg","HS256")

        String token = JWT.create()
                .withHeader(head)
                .withClaim(USER_NO,userNo)
                .withClaim(USER_NAME,userName)
                .withExpiresAt(expDate)
                .sign(Algorithm.HMAC256(SECRET))
        return token
    }

    /**
     * 解密
     * @param token
     * @return
     */
    public static Map  verifyToken(String token){
        def decodedJWT
        try{
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            decodedJWT = jwtVerifier.verify(token).getClaims()
        }catch (Exception e){
            //e.printStackTrace()
            //throw new RuntimeException("登录凭证已过期").printStackTrace()
            println "java.lang.RuntimeException: 登录凭证已过期"
        }finally{
            return decodedJWT
        }
    }

    /**
     * 根据token获取用户
     * @param token
     */
    public static verifyUserByToken(String token){
        def verify = verifyToken(token)
        def user = new HashMap<String,String>()
        if(verify){
            //user = verify.get(USER_NO).asString()
            //println "verify.get(USER_NO).asString():${verify.get(USER_NO).asString()}"
            user.put(USER_NO,verify.get(USER_NO).asString())
            user.put(USER_NAME,verify.get(USER_NAME).asString())
        }
        return user
    }
}
